
package net.yangying.androidframework.core.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.yangying.androidframework.R;
import net.yangying.androidframework.util.Constant;
import net.yangying.androidframework.util.SDCardUtil;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;


/**
 * @author YANGYING
 * @date 2011-7-11
 */
public class UpdateService extends Service {
	
	private static final String TAG = UpdateService.class.getSimpleName();

	private static final int TIMEOUT = 10 * 1000;// 超时
	
    private String appname;
    private String verName;
    private String apkurl;
//    private String apkname;

    private File updateDir = null;
    private File updateFile = null;

    private NotificationManager notificationManager = null;
    private Notification notification = null;

    private Intent updateIntent = null;
    private PendingIntent pendingIntent = null;

    private final static int DOWNLOAD_COMPLETE = 0;
    private final static int DOWNLOAD_FAIL = 1;

    private RemoteViews contentView;
    private int notification_id = 0;
    
    /*
     * (non-Javadoc)
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
	
    private void handleCommand(Intent intent)
    {      
    	if(intent != null) {
    		if(intent.hasExtra("appname"))
    	        appname =intent.getExtras().getString("appname");
    	    if(intent.hasExtra("apkurl"))
    	        apkurl = intent.getExtras().getString("apkurl");	
    	} else {
    		UpdateService.this.stopSelf();
    	}
	    
        
      if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
              .getExternalStorageState())) {
          updateDir = new File(SDCardUtil.getAppSDCardPath());
          updateFile = new File(updateDir.getAbsolutePath() + File.separator + Constant.TEMP_APK);
      }
      
//      updateIntent = new Intent();
//      pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
//      notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//      notification = new Notification();
//
//      notification.icon = R.drawable.logo;
//      notification.tickerText = getString(R.string.download);
//      notification.flags=Notification.FLAG_AUTO_CANCEL;
//      notification.setLatestEventInfo(this, updateFile.getAbsolutePath(), getString(R.string.downloading)+"", pendingIntent);
//      notificationManager.notify(0, notification);
      
     
    }
    
    @Override
    public void onStart(Intent intent,int startId)
    {
        handleCommand(intent);
        createNotification();
        new Thread(new updateRunnable()).start();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        handleCommand(intent);
        createNotification();
        new Thread(new updateRunnable()).start();
        return super.onStartCommand(intent, flags, startId);
//        return 1;
    }
    
	public void createNotification() {		
		/**
		 * 系统默认通知栏
		 */
//		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//		 notification = new Notification();
//		 notification.icon = R.drawable.logo;
//		 // 这个参数是通知提示闪出来的值.
//		 notification.tickerText = "开始下载";
//		 updateIntent = new Intent(this, SplashActivity.class);
//		 pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
//		 notification.setLatestEventInfo(this, appname, "下载：0%",pendingIntent);
//		 notificationManager.notify(notification_id, notification);
		 
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.logo, appname,  System.currentTimeMillis());
		contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
		contentView.setTextViewText(R.id.notificationTitle, getString(R.string.downloading));
		notification.contentView = contentView;
//		updateIntent = new Intent(this, MainTabActivity.class);
		updateIntent = new Intent(this, null);
		pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
		notification.contentIntent = pendingIntent;
		notificationManager.notify(0, notification);
		 
		/***
		 * 在这里我们用自定的view来显示Notification
		 */
//		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//		notification = new Notification(R.drawable.logo, appname,  System.currentTimeMillis());
//		contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
//		contentView.setTextViewText(R.id.notificationTitle, "正在下载");
//		contentView.setTextViewText(R.id.notificationPercent, "0%");
//		contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
//		notification.contentView = contentView;
		
//		updateIntent = new Intent(this, SplashActivity.class);
//		updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//		pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
//		notification.contentIntent = pendingIntent;
//		
//		notificationManager.notify(notification_id, notification);
	}
	
    private Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_COMPLETE:
                    Uri uri = Uri.fromFile(updateFile);
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                    installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                    pendingIntent = PendingIntent.getActivity(UpdateService.this, 0,installIntent, 0);
                    notification.tickerText=getString(R.string.download_completed);
                    notification.setLatestEventInfo(UpdateService.this, appname, getString(R.string.download_completed),pendingIntent);
                    notificationManager.notify(notification_id, notification);
                    stopService(updateIntent);
                    break;
                case DOWNLOAD_FAIL:
                    notification.tickerText=getString(R.string.download_fail);
                    notification.setLatestEventInfo(UpdateService.this, appname+verName, getString(R.string.download_fail),pendingIntent);
                    notificationManager.notify(notification_id, notification);
                    stopService(updateIntent);
                    break;
                default:
                	stopService(updateIntent);
            }
        }
    };
    class updateRunnable implements Runnable {
        Message message = updateHandler.obtainMessage();

        public void run() {
            try {
                if (!updateDir.exists()) {
                    updateDir.mkdirs();
                }
                if (!updateFile.exists()) {
                    updateFile.createNewFile();
                }
                long downloadSize = downloadUpdateFile(apkurl,updateFile.getAbsolutePath());
                if (downloadSize > 0) {
                	message.what = DOWNLOAD_COMPLETE;
                    updateHandler.sendMessage(message);
                }
            } catch (Exception ex) {
                Log.e(TAG, ""+ex.getMessage());
                message.what = DOWNLOAD_FAIL;
                updateHandler.sendMessage(message);
            }
        }
    }

	/***
	 * 下载文件
	 * 
	 * @return
	 * @throws IOException 
	 */
	public long downloadUpdateFile(String down_url, String file) throws IOException  {
		int down_step = 10;// 提示step
		int totalSize;// 文件总大小
		int downloadCount = 0;// 已经下载好的大小
		int updateCount = 0;// 已经上传的文件大小
		InputStream inputStream;
		OutputStream outputStream;

		URL url = new URL(down_url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		httpURLConnection.setConnectTimeout(TIMEOUT);
		httpURLConnection.setReadTimeout(TIMEOUT);
		// 获取下载文件的size
		totalSize = httpURLConnection.getContentLength();
		if (httpURLConnection.getResponseCode() == 404) {
			throw new IOException("fail!404");
		}
		inputStream = httpURLConnection.getInputStream();
		outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
		byte buffer[] = new byte[1024];
		int readsize = 0;
//		Log.d("D","totalSize:"+totalSize);
		while ((readsize = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, readsize);
			downloadCount += readsize;// 时时获取下载到的大小
//			Log.d("D","downloadCount:"+downloadCount);
			/**
			 * 每次增张10%
			 */
			if (updateCount == 0
					|| (downloadCount * 100 / totalSize - down_step) >= updateCount) {
				updateCount += down_step;
//				Log.d("D","updateCount:"+updateCount);
				// 改变通知栏
//				 notification.setLatestEventInfo(this, "正在下载...", updateCount + Constants.PERCENT + "", pendingIntent);
				 //若设置，则会提示太过频繁
//				notification.tickerText = getString(R.string.downloading)+ updateCount + Constants.PERCENT;
				contentView.setTextViewText(R.id.notificationPercent,updateCount + Constant.PERCENT);
				contentView.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
				notificationManager.notify(notification_id, notification);
			}

		}
		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
		}
		inputStream.close();
		outputStream.close();

		return downloadCount;

	}

}
